package com.campus.server.dao;

import com.campus.common.util.DBUtil;
import com.campus.common.vo.Admin;

import java.sql.*;

public class AdminDao {
    public boolean isRegister(String username, String password, Admin admin) {
        try (Connection conn = DBUtil.getConnection(); //从DBUtil获取数据库连接
             Statement st = conn.createStatement(); //创建Statement对象用于执行SQL
             ResultSet rs = st.executeQuery("SELECT * FROM user1")) { //执行查询，返回结果集
            //遍历结果集的每一行
            while (rs.next()) {
                if (rs.getString("username").equals(username)) {
                    return false;
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
        int rows_1=0;
        int rows_2=0;
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                     "INSERT INTO user1 (username, password, role) VALUES (?, ?, ?)")) {
            conn.setAutoCommit(true);  // 确保立即提交
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, "管理员");
            rows_1 = ps.executeUpdate();
            System.out.println("更新行数: " + rows_1); // 调试用
        } catch (Exception e) { e.printStackTrace(); }

        String adminId = admin.getAdminId();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                     "INSERT INTO admin (adminId) VALUES (?) ")) {
            conn.setAutoCommit(true);  // 确保立即提交
            ps.setString(1, adminId);
            System.out.println("更新行数: " + rows_2); // 调试用
            rows_2 = ps.executeUpdate();
            return rows_1*rows_2 > 0;
        } catch (Exception e) { e.printStackTrace(); }
        return false;
    }
}